package com.jinglu.cloud.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinglu.cloud.common.model.vo.PageVO;
import com.jinglu.cloud.common.model.dto.BasePageDTO;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author lvzhenzhao
 * @Datetime 2021/03/02-下午2:27
 */
public class BeanUtils {


    public static <T, E> T convertObject(E source, Class<T> clazz){
        return source != null ? BeanUtil.copyProperties(source, clazz) : null;
    }

    /**
     * 批量转换
     * @param sourceList
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T, E> List<T> convertList(List<E> sourceList, Class<T> clazz) {
        List<T> targetList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sourceList)) {
            sourceList.stream().forEach(source -> {
                T target = BeanUtil.copyProperties(source, clazz);
                targetList.add(target);
            });
        }
        return targetList;
    }

    /**
     * 构建分页VO
     * @param beanPage 分页列表
     * @param clazz    目标类
     * @return
     */
    public static <T, E> PageVO<T> buildPageVO(IPage<E> beanPage, Class<T> clazz) {
        PageVO<T> page = new PageVO<>();
        page.setTotal(beanPage.getTotal());
        List<T> list = convertList(beanPage.getRecords(), clazz);
        page.setDataList(list);
        return page;
    }

    /**
     * 构建分页请求
     * @param pageDTO
     * @param <T>
     * @return
     */
    public static<T> Page<T> buildPageRequest(BasePageDTO pageDTO) {
        Page<T> page = new Page<T>();
        page.setCurrent(pageDTO.getPageNum());
        page.setSize(pageDTO.getPageSize());
        return page;
    }

}
